import { useState, useRef, useEffect, useMemo } from 'react';
import { View, Input } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import styles from './index.module.less';
import { useRequest } from 'ahooks';
import { getCode, updateUserPhone, loginWithCode } from '@/service';
import { useUserStore } from '@/common/hox/userStore';

const tabBarPages = [
    '/pages/index/index',
    '/pages/movie/index',
    '/pages/order/index',
    '/pages/my/index',
];

const PhoneLogin = (props: { isCheck: Boolean; type?: string }) => {
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const timerRef = useRef<NodeJS.Timeout | null>(null);
    const { loginAsync, refreshUser, clear, reAuthAsync } = useUserStore();
    const { run: requestCode } = useRequest(getCode, { manual: true });
    const {
        params: { navUrl: encodeUrl },
    } = useRouter<{ navUrl?: string }>();
    const navUrl = useMemo(
        () => (encodeUrl ? decodeURIComponent(encodeUrl) : undefined),
        [encodeUrl]
    );
    const afterClose = async () => {
        if (navUrl && navUrl !== undefined) {
            if (tabBarPages.find((item) => navUrl.includes(item))) {
                Taro.switchTab({ url: navUrl });
            } else Taro.redirectTo({ url: navUrl });
            return;
        }
        if (process.env.TARO_ENV == 'weapp') {
            Taro.navigateBack({
                delta: 2,
            });
        } else {
            Taro.navigateBack();
        }
    };
    // 获取验证码
    const sendCode = () => {
        if (countdown > 0) return;
        if (!/^1\d{10}$/.test(phone)) {
            Taro.showToast({ title: '请输入正确的手机号', icon: 'none' });
            return;
        }
        requestCode(phone);
        setCountdown(60);
        timerRef.current = setInterval(() => {
            setCountdown((prev) => {
                if (prev <= 1) {
                    clearInterval(timerRef.current!);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
    };
    // 登录
    const signIn = useRequest(props.type === 'BindUser' ? updateUserPhone : loginWithCode, {
        manual: true,
        onSuccess: async (res) => {
            if (res?.accessToken || res?.data.accessToken) {
                await clear();
                await reAuthAsync();
                refreshUser();
                Taro.setStorageSync('token', res?.accessToken || res?.data.accessToken);
                await loginAsync();
                refreshUser();
                afterClose();
            }
        },
    });

    const handleLogin = () => {
        if (!/^1\d{10}$/.test(phone)) {
            Taro.showToast({ title: '请输入正确的手机号', icon: 'none' });
            return;
        }
        if (!code) {
            Taro.showToast({ title: '请输入验证码', icon: 'none' });
            return;
        }
        if (!props.isCheck) {
            Taro.showToast({ title: '请先阅读并同意协议', icon: 'none' });
            return;
        }
        signIn.run({
            mobile: phone,
            verifyCode: code,
        });
    };
    useEffect(() => {
        return () => {
            if (timerRef.current) clearInterval(timerRef.current);
        };
    }, []);

    return (
        <>
            <View className={styles['phone-login']}>
                <View className={styles['phone-row']}>
                    <Input
                        style={{fontSize: '16px'}}
                        type="number"
                        placeholder="请输入手机号"
                        value={phone}
                        onInput={(e) => setPhone(e.detail.value)}
                        maxlength={11}
                    />
                </View>
                <View className={styles['code-row']}>
                    <Input
                        style={{fontSize: '16px'}}
                        type="number"
                        placeholder="请输入验证码"
                        value={code}
                        onInput={(e) => setCode(e.detail.value)}
                        maxlength={6}
                    />
                    <View className={`${styles.code}${countdown > 0 ? ` ${styles.disabled}` : ''}`} onClick={sendCode}>
                        {countdown > 0 ? `${countdown}s后重试` : '获取验证码'}
                    </View>
                </View>
            </View>
            <View className={styles['login-btn']} onClick={handleLogin}>
                {props.type === 'BindUser' ? '绑定手机号' : '登录'}
            </View>
        </>
    );
};

export default PhoneLogin;
